/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.domain.vo;

import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 算子参数配置path树结构视图层vo
 *
 * @author hxloongs
 * @date 2024-7-10
 */
@Data
public class IsfdOperatorParameterConfigPathTreeVo {

    private String path;

    private String fullPath;

    private List<IsfdOperatorParameterConfigPathTreeVo> children;

    public IsfdOperatorParameterConfigPathTreeVo(String path, String fullPath) {
        this.path = path;
        this.fullPath = fullPath;
        this.children = new ArrayList<>();
    }

    public static IsfdOperatorParameterConfigPathTreeVo buildTree(List<String> paths) {
        Map<String, IsfdOperatorParameterConfigPathTreeVo> nodeMap = new HashMap<>();
        IsfdOperatorParameterConfigPathTreeVo root = null;

        for (String path : paths) {
            String[] parts = path.split("/");
            IsfdOperatorParameterConfigPathTreeVo currentParent = root;
            StringBuilder fullPathBuilder = new StringBuilder();

            for (int i = 1; i < parts.length; i++) { // Skip the first empty part due to leading slash
                String folderName = parts[i];
                fullPathBuilder.append("/").append(folderName);
                String fullPath = fullPathBuilder.toString();

                // Check if the node already exists in the map
                IsfdOperatorParameterConfigPathTreeVo childNode = nodeMap.get(fullPath);
                if (childNode == null) {
                    // Create a new node and add it to the map
                    childNode = new IsfdOperatorParameterConfigPathTreeVo(folderName, fullPath);
                    nodeMap.put(fullPath, childNode);
                }

                // Add the child node to the current parent's children list
                if (currentParent != null && !currentParent.children.contains(childNode)) {
                    currentParent.children.add(childNode);
                }

                // Move down the tree
                currentParent = childNode;
            }

            // Set the root if it's the first iteration
            if (root == null) {
                root = new IsfdOperatorParameterConfigPathTreeVo("", ""); // Empty string for root path and full path
                root.children.add(currentParent);
            }
        }

        // set root path and fullPath
        if (root == null) {
            root = new IsfdOperatorParameterConfigPathTreeVo("/", "/");
        } else {
            root.setPath("/");
            root.setFullPath("/");
        }
        return root;
    }

}
